package codec

import (
	"github.com/xcy8712622040/gnetws"
	"io"
	"sync"
)

type ProtoSerialize struct {
	pool *sync.Pool // 使用对象池重复利用减少gc
}

func NewProtoSerialize() *ProtoSerialize {
	return &ProtoSerialize{
		pool: new(sync.Pool),
	}
}

func (p *ProtoSerialize) NewEnCodec(w io.Writer) gnetws.Encode {
	var codec *ProtoCodec

	element := p.pool.Get()
	if element != nil {
		codec = element.(*ProtoCodec)
	} else {
		codec = &ProtoCodec{
			serialize: p,
		}
	}

	codec.writer = w

	return codec
}

func (p *ProtoSerialize) NewDeCodec(r io.Reader) gnetws.Decode {
	var codec *ProtoCodec

	element := p.pool.Get()
	if element != nil {
		codec = element.(*ProtoCodec)
	} else {
		codec = &ProtoCodec{
			serialize: p,
		}
	}

	codec.reader = r

	return codec
}
